#!/usr/bin/python3
# -*-coding:utf-8 -*-
import socket
import cv2
import threading
import os

class GetImageThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        global frame1,frame2
        cap1 = cv2.VideoCapture(0)
        cap1.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M','J','P','G'))
        if(cap1.isOpened()):
            print("carmer2 opened")
        else:
            print("carmer2 not opened")
        cap2 = cv2.VideoCapture(2)
        cap2.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter.fourcc('M','J','P','G'))
        if(cap2.isOpened()):
            print("carmer0 opened")
        else:
            print("carmer0 not opened")

        print ("开始线程：" + self.name)
        while True:
                #cap1 = cv2.VideoCapture(2)
                ret1, frame1 = cap1.read()
                #print ("fuckyou1")
                #cap1.release()
                #cap2 = cv2.VideoCapture(0)
                ret2, frame2 = cap2.read()
                #print ("fuckyou2")
                #cap2.release()
        cap1.release()
        cap2.release()
        print ("退出线程：" + self.name)

class CommThread(threading.Thread):
        def __init__(self, threadID, name, counter):
                threading.Thread.__init__(self)
                self.threadID = threadID
                self.name = name
                self.counter = counter
        def run(self):
                print ("开始线程：" + self.name)
                global frame
                sock = socket.socket()
                host = socket.gethostname()
                port = 12345
                sock.bind ((host,port))
                sock.listen(5)
                i = 0
                #os.system("python3 demo_auto.py")
                while(True):
                        c,addr = sock.accept()
                        while True :
                            data = c.recv(100)
                            if  data  ==  b'##':
                                    print("send")
                                    cv2.imwrite("server1.jpg",frame1)
                                    cv2.imwrite("server2.jpg",frame2)
                                    i += 1
                                    if i == 2:
                                        i = 0
                                        break
                sock.close()
                print ("退出线程：" + self.name)

global frame
if __name__ ==  '__main__':
        # global frame
        # 创建新线程
        thread1 = GetImageThread(1, "Camera", 1)
        thread2 = CommThread(2, "Communication", 2)

        # 开启新线程
        thread1.start()
        thread2.start()
        # thread1.join()
        # thread2.join()
        print ("退出主线程")
# sock.close()
# cv2.destroyAllWindows()
